<template>
  <div class="vendorPSR">
    <div class="vendorPSR_top">
      <p style="margin: 2px 6px 0 0">厂商</p>
      <input
        class="inp inp3"
        type="text"
        v-model="no"
        @blur="manufacturerNoBlur"
      />
      <div class="sty">
        <el-select v-model="no" @change="manufacturerChange">
          <el-option
            v-for="item in manufacturerList"
            :key="item.value"
            :label1="item.label1"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left; margin-right: 10px">{{
              item.label1
            }}</span>
            <span style="float: right">{{ item.label }}</span></el-option
          >
        </el-select>
      </div>
      <p class="jl">款号</p>
      <div class="sty2">
        <el-input v-model="kindsNumber"></el-input>
        <!-- <el-select v-model="kindsNumber">
          <el-option v-for="item in kindsNumberList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select> -->
      </div>
      <p class="jl">销货日期</p>
      <div class="block">
        <el-date-picker
          v-model="timeData"
          type="daterange"
          size="mini"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          class="data-pick"
          unlink-panels
        ></el-date-picker>
      </div>
      <p class="jl">季度</p>
      <div class="sty2">
        <el-select
          v-model="quarterListStr"
          multiple
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in quartListStrList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
    </div>
    <div class="button_box">
      <div>
        <el-button @click="query" type="primary" icon="el-icon-search"
          >查询</el-button
        >
        <el-button @click="exportData" icon="el-icon-upload2">导出</el-button>
      </div>
      <el-checkbox
        v-model="styleNumberFlag"
        label="款号货号合计"
        border
      ></el-checkbox>
    </div>
    <div>
      <el-table
        :data="tableData1"
        :header-cell-style="{
          background: '#f4f4f4',
          padding: 0,
          height: '40px'
        }"
        :cell-style="{ padding: 0, height: '36px' }"
        show-summary
        :summary-method="getSummaries"
        ref="table"
        highlight-current-row
        @row-click="rowClick"
        style="width: 100%"
        height="40vh"
      >
        <el-table-column
          prop="manufacturerNo"
          label="厂商编号"
          align="center"
          width="90"
        ></el-table-column>
        <el-table-column
          prop="manufacturerName"
          label="厂商简称"
          align="center"
        ></el-table-column>
        <el-table-column label="销售比" align="center">
          <el-table-column
            prop="quantityRatio"
            label="数量比"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="amountRatio"
            label="金额比"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="厂商进货" align="center">
          <el-table-column
            prop="factoryInput"
            label="厂进"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="factoryRevenue"
            label="厂进额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="厂商退货" align="center">
          <el-table-column
            prop="factoryOutput"
            label="厂退"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="factoryRefund"
            label="厂退额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="厂商实进" align="center">
          <el-table-column
            prop="factoryRealProgress"
            label="厂实进"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="actualAmount"
            label="实进额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="客户销售" align="center">
          <el-table-column
            prop="sell"
            label="销售"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="sales"
            label="销售额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="库存" align="center">
          <el-table-column
            prop="stock"
            label="库存"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="inventory"
            label="库存额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="客存" align="center">
          <el-table-column
            prop="guestDeposit"
            label="客存"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="customerDeposit"
            label="客存额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
        <el-table-column label="总存" align="center">
          <el-table-column
            prop="totalDeposit"
            label="总存"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="totalDepositAmount"
            label="总存额"
            align="center"
            width="90"
          ></el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 2vh">
      <el-table
        :data="tableData2"
        :header-cell-style="{
          background: '#f4f4f4',
          padding: 0,
          height: '40px'
        }"
        :cell-style="{ padding: 0, height: '36px' }"
        style="width: 100%"
        height="36vh"
      >
        <el-table-column
          prop="styleColorNumber"
          label="款号色号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="salesRatio"
          label="销售比"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="manufacturerPurchase"
          label="厂商进货"
        ></el-table-column>
        <el-table-column
          prop="manufacturerReturns"
          label="厂商退货"
        ></el-table-column>
        <el-table-column
          prop="customerSales"
          label="客户销货"
        ></el-table-column>
        <el-table-column
          prop="customerSalesRefund"
          label="客户销退"
        ></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="sellingPrice" label="售价"></el-table-column>
        <el-table-column prop="brandName" label="品牌"></el-table-column>
      </el-table>
    </div>
    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      :tableTypeChange="tableTypeChange"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
    <!-- <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span>
        <span>记录数：{{amount}}</span>
      </div>
    </foot-view> -->
  </div>
</template>
<script>
import footView from '../../../components/FootView'
import {
  getManufacturer,
  getInOut,
  getANumber,
  factoryPinDetail
} from '../../../network/manufacturer'
import { getQuarter } from '../../../network/quarter'
import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'
import XLSX from 'xlsx'
export default {
  name: 'vendor_purchase_sales_ratio',
  mixins: [today, enterUp],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null

    this.inpList = this.getInput()
    //季度
    getQuarter().then((res) => {
      // console.log(res.data)
      let qList = res.data.data
      qList.forEach((e) => {
        this.quartListStrList.push({ label: e.name, value: e.id })
      })
    })

    //厂商数据
    this.timeData = [this.getLastWeek(), this.getNowTime()]

    getManufacturer().then((res) => {
      // console.log(res.data.data)
      if (!res.data.data) return
      res.data.data.forEach((element) => {
        this.manufacturerList.push({
          label: element.name,
          value: element.no,
          label1: element.no
        })
      })
    })
  },
  data() {
    return {
      inpList: [],
      timeData: null,
      manufacturerList: [],
      no: '',
      manufacturerName: '',
      kindsNumber: '',
      kindsNumberList: [],
      quarterListStr: '',
      selectHeaderList: [],
      headerList: [], //foot-view

      quartListStrList: [],
      styleNumberFlag: false,
      tableData1: [],
      tableData2: [],
      jxQuarter: null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
      amount: 0,

      summation: [],

      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      tableTypeChange: false
    }
  },
  methods: {
    rowClick(e) {
      this.manufacturerName = e.manufacturerNo
      this.getDetail()
    },

    query() {
      this.manufacturerName = ''
      let name = ''
      for (const o of this.manufacturerList) {
        if (o.value == this.no) {
          name = o.label
          break
        }
      }
      let obj = {
        manufacturerNo: this.no,
        kindsNumber: this.kindsNumber,
        quarterIds: this.quarterListStr.toString()
      }
      if (this.timeData) {
        obj.startDate = this.timeData[0].slice(0, 10).replace(/-/g, '/')
        obj.endDate = this.timeData[1].slice(0, 10).replace(/-/g, '/')
      }
      this.tableData1 = []
      this.tableData2 = []
      this.amount = 0
      getInOut(obj).then((res) => {
        // console.log(res)
        this.tableData1 = res.data.data || []
        this.amount = this.tableData1.length
        this.tableData1.forEach((e) => {
          e.quantityRatio = (e.quantityRatio * 100).toFixed(2) + '%'
          e.amountRatio = (e.amountRatio * 100).toFixed(2) + '%'
        })
        if (!this.tableData1.length) {
          this.$message.info('暂无数据')
        } else {
          this.getDetail()
        }
        this.$nextTick(() => {
          this.$refs.table.doLayout()
        })
      })
    },
    getDetail() {
      let obj = {
        'pageData.limit': this.limit,
        'pageData.page': this.currentPage,
        manufacturerNoList: this.manufacturerName,
        isDisplayKindsNumber: this.styleNumberFlag
      }
      if (this.timeData) {
        obj.startDate = this.timeData[0].slice(0, 10).replace(/-/g, '/')
        obj.endDate = this.timeData[1].slice(0, 10).replace(/-/g, '/')
      }
      factoryPinDetail(obj).then((res) => {
        this.tableData2 = res.data.data || []
        this.tableData2.forEach((e) => {
          e.styleColorNumber = e.styleNumber + '-' + e.colorNo
          e.salesRatio = (e.salesRatio * 100).toFixed(2) + '%'
        })
        this.dataLen = res.data.total
      })
    },
    manufacturerChange(e) {
      // console.log(e)
      this.manufacturerName = e
      // this.getKN()
    },
    manufacturerNoBlur() {
      if (this.no != '') {
        for (const i of this.manufacturerList) {
          if (this.no == i.value) {
            this.manufacturerName = i.value
            // this.getKN()
            return
          }
        }
        this.$alert('无此厂商编号', '', {
          confirmButtonText: '确定'
        })
        this.no = ''
        this.manufacturerName = ''
      } else {
        this.manufacturerName = ''
      }
    },

    getKN() {
      this.kindsNumberList = []
      getANumber({ supplier: this.manufacturerName }).then((res) => {
        let list = res.data.data || []
        list.forEach((e) => {
          this.kindsNumberList.push({
            label: e.kindsNumber,
            value: e.kindsNumber
          })
        })
      })
    },

    exportData() {
      let header = {}
      //表格数据
      let data = {}
      let index = 6

      let output = {}
      let ref = ''
      let merges = []
      let wb = {}

      header = {
        A1: { v: '厂商编号' },
        B1: { v: '厂商简称' },

        C1: { v: '销售比' },
        E1: { v: '厂商进货' },
        G1: { v: '厂商退货' },
        I1: { v: '厂商实进' },
        K1: { v: '客户销售' },
        M1: { v: '库存' },
        O1: { v: '客存' },
        Q1: { v: '总存' },

        C2: { v: '数量比' },
        D2: { v: '金额比' },
        E2: { v: '厂进' },
        F2: { v: '厂进额' },
        G2: { v: '厂退' },
        H2: { v: '厂退额' },
        I2: { v: '厂实进' },
        J2: { v: '实进额' },
        K2: { v: '销售' },
        L2: { v: '销售额' },
        M2: { v: '库存' },
        N2: { v: '库存额' },
        O2: { v: '客存' },
        P2: { v: '客存额' },
        Q2: { v: '总存' },
        R2: { v: '总存额' }
      }
      index = 3
      this.tableData1.forEach((e) => {
        data['A' + index] = { v: e.manufacturerNo }
        data['B' + index] = { v: e.manufacturerName }
        data['C' + index] = { v: e.quantityRatio }
        data['D' + index] = { v: e.amountRatio }
        data['E' + index] = { v: e.factoryInput }
        data['F' + index] = { v: e.factoryRevenue }
        data['G' + index] = { v: e.factoryOutput }
        data['H' + index] = { v: e.factoryRefund }
        data['I' + index] = { v: e.factoryRealProgress }
        data['J' + index] = { v: e.actualAmount }
        data['K' + index] = { v: e.sell }
        data['L' + index] = { v: e.sales }
        data['M' + index] = { v: e.stock }
        data['N' + index] = { v: e.inventory }
        data['O' + index] = { v: e.guestDeposit }
        data['P' + index] = { v: e.customerDeposit }
        data['Q' + index] = { v: e.totalDeposit }
        data['R' + index] = { v: e.totalDepositAmount }
        index++
      })

      data['A' + index] = { v: '合计：' }
      // data['C'+index] = {v: this.summation[]}
      // data['D'+index] = {v: this.summation[]}
      data['E' + index] = { v: this.summation[4] }
      data['F' + index] = { v: this.summation[5] }
      data['G' + index] = { v: this.summation[6] }
      data['H' + index] = { v: this.summation[7] }
      data['I' + index] = { v: this.summation[8] }
      data['J' + index] = { v: this.summation[9] }
      data['K' + index] = { v: this.summation[10] }
      data['L' + index] = { v: this.summation[11] }
      data['M' + index] = { v: this.summation[12] }
      data['N' + index] = { v: this.summation[13] }
      data['O' + index] = { v: this.summation[14] }
      data['P' + index] = { v: this.summation[15] }
      data['Q' + index] = { v: this.summation[16] }
      data['R' + index] = { v: this.summation[17] }
      index++

      // 合并 headers 和 data
      output = Object.assign({}, header, data)
      // 表格范围，范围越大生成越慢
      ref = 'A1:R' + (this.tableData1.length + 10)
      //合并单元格设置
      merges = [
        { s: { c: 0, r: 0 }, e: { c: 0, r: 1 } },
        { s: { c: 1, r: 0 }, e: { c: 1, r: 1 } },
        { s: { c: 2, r: 0 }, e: { c: 3, r: 0 } },
        { s: { c: 4, r: 0 }, e: { c: 5, r: 0 } },
        { s: { c: 6, r: 0 }, e: { c: 7, r: 0 } },
        { s: { c: 8, r: 0 }, e: { c: 9, r: 0 } },
        { s: { c: 10, r: 0 }, e: { c: 11, r: 0 } },
        { s: { c: 12, r: 0 }, e: { c: 13, r: 0 } },
        { s: { c: 14, r: 0 }, e: { c: 15, r: 0 } },
        { s: { c: 16, r: 0 }, e: { c: 17, r: 0 } }
      ]
      // 构建 workbook 对象
      wb = {
        SheetNames: ['厂商进销比'],
        Sheets: {
          厂商进销比: Object.assign({}, output, {
            '!ref': ref,
            '!merges': merges
          })
        }
      }

      // 导出 Excel
      XLSX.writeFile(wb, '厂商进销比.xlsx')
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map((item) => Number(item[prop]))
        if (!values.every((value) => isNaN(value))) {
          if (
            prop == 'factoryInput' ||
            prop == 'factoryRevenue' ||
            prop == 'factoryOutput' ||
            prop == 'factoryRefund' ||
            prop == 'factoryRealProgress' ||
            prop == 'actualAmount' ||
            prop == 'sell' ||
            prop == 'sales' ||
            prop == 'stock' ||
            prop == 'inventory' ||
            prop == 'guestDeposit' ||
            prop == 'customerDeposit' ||
            prop == 'totalDeposit' ||
            prop == 'totalDepositAmount'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      // console.log(sums)
      this.summation = sums
      return sums
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      this.currentPage = 1
      this.tableTypeChange = !this.tableTypeChange
      this.getDetail()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDetail()
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    limit(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    no(a, b) {
      this.no = a.toUpperCase().trim()
    }
  },
  components: {
    footView
  }
}
</script>

<style scoped>
.vendorPSR {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.vendorPSR_top {
  display: flex;
  padding: 1vh 0;
  border-bottom: 2px solid #f4f4f4;
  white-space: nowrap;
}
.vendorPSR input:focus {
  outline: none;
  border: 1px solid #017aff;
}
.inp {
  border: 1px solid #dbdbdb;
  border-radius: 3px;
  height: 30px;
  padding: 0 15px;
}
.inp3 {
  width: 60px;
  margin-right: 10px;
}
.jl {
  margin: 2px 6px 0 10px;
}
.button_box {
  display: flex;
  justify-content: space-between;
  margin: 1vh 0;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
</style>

<style>
.vendorPSR .el-input__icon {
  line-height: 30px;
}
.vendorPSR .vendorPSR_top .sty .el-input__inner {
  height: 30px;
  width: 100px;
}
.vendorPSR .vendorPSR_top .sty2 .el-input__inner {
  height: 30px;
  width: 160px;
}
.vendorPSR .vendorPSR_top .block .el-input__inner {
  height: 30px;
  width: 350px;
}
.vendorPSR .vendorPSR_top .block .el-input__icon {
  line-height: 23px;
}
.vendorPSR .vendorPSR_top .block .el-date-editor .el-range-separator {
  width: 8%;
}
/* .vendorPSR .vendorPSR_top .block .el-date-editor .el-range-separator{
    padding: 0;
    margin-top: -9px;
  } */
.vendorPSR .button_box .el-checkbox.is-bordered {
  padding: 4px 5px 9px 5px;
  height: 30px;
}
.vendorPSR .el-range-editor--mini .el-range-input {
  font-size: 15px;
}
.vendorPSR .el-table__footer .cell {
  padding: 0;
}
</style>
